import time
from datetime import datetime, timedelta

from flask import current_app
from flask import g
from flask import redirect
from flask import render_template, jsonify
from flask import request
from flask import session
from flask import url_for

from info import constants, db
from info.models import User, News, Category
from info.utils.common import login_data
from info.utils.image_storage import storage
from info.utils.response_code import *
from . import admin_blue


# 后台登录视图
@admin_blue.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'GET':
        # 若已经状态保持则直接跳转首页
        is_id = session.get('user_id', None)
        is_admin = session.get('is_admin', False)
        if is_id and is_admin:
            return redirect(url_for('admin.index'))
        return render_template('admin/login.html')

    # POST 请求登录
    # 1.获取参数
    username = request.form.get('username')
    password = request.form.get('password')

    # 2.校验有效性
    if not all([username, password]):
        return render_template('admin/login.html', errmsg='参数不全')

    # 3.处理对比逻辑
    try:
        user = User.query.filter(User.nick_name==username, User.is_admin==True).first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据库查询错误')

    if not user or not user.check_passowrd(password):
        return render_template('admin/login.html', errmsg='账户或密码错误')

    # 登录完成状态保持
    session['user_id'] = user.id
    session['nick_name'] = user.nick_name
    session['mobile'] = user.mobile
    session['is_admin'] = user.is_admin

    # 4.返回成功
    return redirect(url_for('admin.index'))


# 退出
@admin_blue.route('/logout')
def logout():
    session.pop('nick_name', None)
    session.pop('mobile', None)
    session.pop('user_id', None)
    session.pop('is_admin', None)
    return redirect(url_for('admin.login'))


# 后台管理中心
@admin_blue.route('/index')
@login_data
def index():
    user = g.user
    data = {
        'user': user.to_dict()
    }
    return render_template('admin/index.html', data=data)


# 用户统计
@admin_blue.route('/user_count')
def user_count():
    # 查询数据库，获取所有用户（除管理员）数量
    user_count = 0
    try:
        user_count = User.query.filter(User.is_admin == False).count()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据库查询错误')

    # 查询每月新增用户数量(查询的是大于当前月1号0点0分0秒创建的用户（除管理员）)
    # 获取当前时间（以获取当月时间）
    # current_date = datetime.now()
    current_date = time.localtime()  # 这种方法可以获取年 月 日 单独的字符串
    # 把字符串格式的日期转成日期格式
    month_start_date = datetime.strptime('%d-%02d-01' %(current_date.tm_year, current_date.tm_mon), '%Y-%m-%d')

    user_month_added = 0
    try:
        user_month_added = User.query.filter(User.is_admin == False, User.create_time >= month_start_date).count()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='查询数据库错误')

    # 获取每天新增用户数量
    day_start_date = datetime.strptime('%d-%02d-%02d' %(current_date.tm_year, current_date.tm_mon, current_date.tm_mday), '%Y-%m-%d')

    user_day_added = 0
    try:
        user_day_added = User.query.filter(User.is_admin == False, User.create_time > day_start_date).count()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据库查询错误')

    # 显示下方图表(最近31天)
    now_date = datetime.strptime(datetime.now().strftime('%Y-%m-%d'), '%Y-%m-%d')
    active_date = []
    active_count = []

    for i in range(0, 31):
        day_begin = now_date - timedelta(days=i)
        day_end = now_date - timedelta(days=i-1)

        # 将date添加到活跃日期列表中
        active_date.append(day_begin.strftime('%Y-%m-%d'))

        # 查询在当天开始到第二天开始之间有过最近登录记录的用户数量(除管理员)
        count = 0
        # 查询
        try:
            count = User.query.filter(User.is_admin == False, User.last_login >= day_begin, User.last_login < day_end).count()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg='数据库查询错误')
        active_count.append(count)

    active_count.reverse()
    active_date.reverse()

    data = {
        'user_count': user_count,
        'user_month_added': user_month_added,
        'user_day_added': user_day_added,
        'active_count': active_count,
        'active_date': active_date
    }
    return render_template('admin/user_count.html', data=data)


# 用户列表
@admin_blue.route('/user_list')
def user_list():
    # 分页查询用户名，电话，注册时间，上次登录时间（除管理员）
    # 获取参数(当前页码)
    page = request.args.get('page', 1)

    # 页码保证是int
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1

    # 查询数据库(除管理员外的所有用户数据)
    try:
        paginate = User.query.filter(User.is_admin == False).paginate(page, constants.ADMIN_USER_PAGE_MAX_COUNT, False)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据库查询错误')

    user_class_list = paginate.items
    current_page = paginate.page
    total_pages = paginate.pages

    user_list = []
    for user in user_class_list:
        user_list.append(user.to_admin_dict())

    data = {
        'current_page': current_page,
        'total_pages': total_pages,
        'user_list': user_list
    }

    return render_template('admin/user_list.html', data=data)


# 新闻审核
@admin_blue.route('/news_review')
def news_review():
    # 查询新闻id，标题，发布时间，状态
    # 获取当前页
    page = request.args.get('page', 1)
    keywords = request.args.get('keywords', '')
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1
    # 查询数据库(未审核的)
    filters = [News.status != 0]
    if keywords:
        filters.append(News.title.contains(keywords))
    try:
        paginate = News.query.filter(*filters).paginate(page, constants.ADMIN_NEWS_PAGE_MAX_COUNT, False)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据库查询错误')

    news_class_list = paginate.items
    current_page = paginate.page
    total_pages = paginate.pages

    news_list = []
    for news in news_class_list:
        news_list.append(news.to_review_dict())

    data = {
        'current_page': current_page,
        'total_pages': total_pages,
        'news_list': news_list
    }

    return render_template('admin/news_review.html', data=data)


# 审核详情页
@admin_blue.route('/review_detail', methods=['POST', 'GET'])
def review_detail():
    if request.method == 'GET':
        # 获取参数（news_id）
        news_id = request.args.get('news_id')

        # 查询数据库
        try:
            news = News.query.filter(News.id==news_id).first()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg='数据库查询错误')

        data ={
            'news': news.to_dict() if news else None
        }
        return render_template('admin/news_review_detail.html', data=data)

    # 处理post请求，发送审核结果
    # 获取参数
    params = request.json
    action = params.get('action')
    reason = params.get('reason')
    news_id = params.get('news_id')

    # action数据有效性
    if action not in ['accept', 'reject']:
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

    try:
        news = News.query.filter(News.id == news_id).first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据库查询错误')

    # 通过
    if action == 'accept':
        news.status = 0
        news.reason = reason
    # 未通过
    else:
        news.status = -1
        news.reason = reason

    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据库写入错误')

    return jsonify(errno=RET.OK, errmsg='ok')


# 新闻版式编辑
@admin_blue.route('/news_edit')
def news_edit():
    # 获取当前页码
    page = request.args.get('page', 1)
    keywords = request.args.get('keywords', '')

    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1

    filters = []
    if keywords:
        filters.append(News.title.contains(keywords))
    try:
        paginate = News.query.filter(*filters).paginate(page, constants.ADMIN_NEWS_PAGE_MAX_COUNT, False)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据库查询错误')

    news_class_list = paginate.items
    current_page = paginate.page
    total_pages = paginate.pages

    news_list = []
    for news in news_class_list:
        news_list.append(news)

    data = {
        'news_list': news_list,
        'current_page': current_page,
        'total_pages': total_pages
    }
    return render_template('admin/news_edit.html', data=data)


# 新闻编辑详情
@admin_blue.route('/edit_detail', methods=['GET', 'POST'])
def edit_detail():
    if request.method == 'GET':
        # 获取参数
        news_id = request.args.get('news_id')

        try:
            news_id = int(news_id)
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

        try:
            news = News.query.filter(News.id == news_id).first()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg='数据库查询错误')

        try:
            categories = Category.query.filter(Category.id != 1).all()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg='数据库查询错误')

        category_list = []
        for category in categories:
            c_dict = category.to_dict()
            # 在字典中添加了一个用来表示分类选中的键
            c_dict['is_selected'] = False
            if category.id == news.category_id:
                c_dict['is_selected'] = True
            category_list.append(c_dict)

        data = {
            'news': news.to_dict(),
            'category_list': category_list
        }

        return render_template('admin/news_edit_detail.html', data=data)

    # POST请求提交
    # 获取参数
    news_id = request.form.get('news_id')
    title = request.form.get('title')
    category_id = request.form.get('category_id')
    digest = request.form.get('digest')
    content = request.form.get('content')
    index_image = request.files.get('index_image')

    # 2.校验参数（数据有效性，title不超过20个字，分类传过来的id是int类型）
    if not all([title, category_id, digest, content]):
        return jsonify(errno=RET.PARAMERR, errmsg='缺少参数')
    if len(title) > 20:
        return jsonify(errno=RET.PARAMERR, errmsg='标题不超过20个字')
    try:
        category_id = int(category_id)
    except Exception as e:
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据库查询错误')

    news.title = title
    news.category_id = category_id
    news.digest = digest
    news.content = content
    news.status = 1

    if index_image:
        try:
            index_image = index_image.read()
        except Exception as e:
            return jsonify(errno=RET.PARAMERR, errmsg='读取图像失败')

        try:
            index_image_url = storage(index_image)
        except Exception as e:
            return jsonify(errno=RET.THIRDERR, errmsg='七牛云存储文件失败')

        news.index_image_url = constants.QINIU_DOMIN_PREFIX + index_image_url

    try:
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据库写入错误')

    return jsonify(errno=RET.OK, errmsg='ok')


# 分类管理
@admin_blue.route('/news_type', methods=['POST', 'GET'])
def news_type():
    if request.method == 'GET':
        try:
            categories = Category.query.all()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg='数据库查询错误')

        category_list = []
        for category in categories:
            category_list.append(category.to_dict())

        data = {
            'category_list': category_list
        }
        return render_template('admin/news_type.html', data=data)

    # 处理POST请求
    # 获取参数
    params = request.json
    id = params.get('id')
    name = params.get('name')

    if not name:
        return jsonify(errno=RET.PARAMERR, errmsg='缺少参数')

    if id:
        # 有id则表示是修改分类名
        # 按id查询数据库
        try:
            category = Category.query.get(id)
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg='数据库查询错误')

        # 修改模型类name
        category.name = name
        try:
            db.session.commit()
        except Exception as e:
            db.session.rollback()
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg='数据库写入错误')

    else:
        # 没有id，新增
        category = Category()
        category.name = name
        try:
            db.session.add(category)
            db.session.commit()
        except Exception as e:
            db.session.rollback()
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg='数据库写入错误')

    return jsonify(errno=RET.OK, errmsg='ok')
